package com.youlin.aop;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.youlin.config.Applets;
import com.youlin.entities.BygAppointment;
import com.youlin.service.BygAppointmentService;
import com.youlin.untils.MyEnum;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Lazy
    @Autowired
    private BygAppointmentService bygAppointmentService;
    @Autowired
    private Applets applets;

    @Async
    public void resetRedisData() {
        redisTemplate.opsForValue().set("takerTel:13811342765", 123456);
    }

    @Async
    public void resetRBloomFilter() {
        RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter(MyEnum.AMBF.getMessage());
        bloomFilter.delete(); // 重新初始化布隆过滤器
        boolean tryInit = bloomFilter.tryInit(100000, 0.01);
        if (tryInit) {
            LambdaQueryWrapper<BygAppointment> wrapper = Wrappers.lambdaQuery(BygAppointment.class)
                    .ge(BygAppointment::getStatus, MyEnum.AM_OPERATE.getValue());
            bygAppointmentService.list(wrapper).parallelStream().forEach(am -> bloomFilter.add(am.getUuId()));
        }
    }

    @Async
    public void switchWxAppletAsync(String wxActive) {
        switchWxApplet(wxActive);
    }

    public Boolean switchWxApplet(String wxActive) {
        try {
            if (StringUtils.isBlank(wxActive)) wxActive = applets.getActive();

            redisTemplate.opsForValue().set(MyEnum.WX_ACTIVE.getMessage(), wxActive);
            redisTemplate.opsForHash().putAll(MyEnum.WX_APPLETS.getMessage(), applets.getApps());

            redisTemplate.delete(MyEnum.ACCESS_TOKEN_KEY.getMessage());

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
